// pages/profile/Profile.js
var network = require("../../api/api.js")
var basicData = require('../../utils/data')
var util = require('../../utils/util')
//获取应用实例
const app = getApp()
Page({

  /**
   * 页面的初始数据
   */
  data: {
    img: "../../images/11.png",
    imgg: "../../images/u5.png",
    imggg: "../../images/u4.png",
    imgggg: "../../images/u8.png",
    imggggg: "../../images/s1.png",
    ObjectData: ['occupation', 'educational', 'technical_title', 'formation', 'org', 'org_lev', 'old_man_touch_rate'],
    isPass: true,
    canvasWidth: '300px',
    canvasHeight: '300px',
    getProfile: {},
    ageIndex: 0,
    ageArray: [],
    sexArray: ['女', '男'],
    selectArray: ['否', '是'],
    orgArray: [{
        id: 1,
        name: '医院'
      },
      {
        id: 2,
        name: '养老院'
      },
      {
        id: 3,
        name: '社区'
      },
      {
        id: 4,
        name: '其他'
      }
    ],
    org_levArray: [{
        id: 1,
        name: '三级甲等'
      },
      {
        id: 2,
        name: '三级乙等'
      },
      {
        id: 3,
        name: '二级甲等'
      },
      {
        id: 4,
        name: '其它'
      }
    ],
    occupationArray: [{
        id: 1,
        name: '医生'
      },
      {
        id: 2,
        name: '护士'
      },
      {
        id: 3,
        name: '其他'
      }
    ],
    educationalArray: [{
        id: 1,
        name: '中专'
      },
      {
        id: 2,
        name: '大专'
      },
      {
        id: 3,
        name: '本科'
      },
      {
        id: 4,
        name: '硕士'
      },
      {
        id: 5,
        name: '博士研究生及以上'
      }
    ],
    technical_titleArray: [{
        id: 1,
        name: '初级（士）'
      },
      {
        id: 2,
        name: '初级（住院师，护师）'
      },
      {
        id: 3,
        name: '中级（主治、主管）'
      },
      {
        id: 4,
        name: '副高级'
      },
      {
        id: 5,
        name: '高级'
      }
    ],
    formationArray: [{
        id: 1,
        name: '在编'
      },
      {
        id: 2,
        name: '合同'
      },
    ],
    old_man_touch_rateArray: [{
        id: 1,
        name: '每日多次'
      },
      {
        id: 2,
        name: '每日一次'
      },
      {
        id: 3,
        name: '每4-5天一次'
      },
      {
        id: 4,
        name: '每周一次'
      },
      {
        id: 5,
        name: '每两周一次'
      },
      {
        id: 6,
        name: '每月一次'
      },
    ],
    selectKey: {
      occupationKey: 0,
      educationalKey: 0,
      technical_titleKey: 0,
      formationKey: 0,
      orgKey: 0,
      org_levKey: 0,
      old_man_touch_rateKey: 0
    }
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    var that = this
    var userLogin = wx.getStorageSync('user_login') || {}
    this.setData({
      isPass: userLogin.audit_status === 2
    })
    this.setData({
      ageArray: basicData.ageData() || []
    })
    var params = new Object()
    params.business_param = {
      user_id: String(userLogin.user_id)
    }
    network.POST({
      params: params,
      url: "get_user_info",
      success: function (res) {
        that.selectObjectDataKey(res.result[0] || {})
        that.setData({
          getProfile: res.result[0] || {}
        })
        //处理调查问卷隐/显问题
        if (res.result[0].show_invest == 0 || res.result[0].show_invest == 1) {
          wx.setStorageSync('show_invest', res.result[0].show_invest);
        }
        //拿到解密后的数据，进行代码逻辑  

      },
      fail: function () {
        //失败后的逻辑  

      },
    })
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {
    this.getBase = this.selectComponent('#toBase')
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function (options) {
    var userLogin = wx.getStorageSync('user_login') || {}
    var that = this
    if (this.data.upload_card) {
      this.setData({
        getProfile: Object.assign({}, this.data.getProfile, this.data.upload_card)
      })
      this.setData({
        upload_card: ''
      })
    }
    if (this.data.select_status) {
      let getProfile = this.data.getProfile
      const select_status = this.data.select_status
      let data = {}
      data[select_status.status + '_status'] = select_status.value
      if (select_status.value === 1) {
        if (select_status.status === 'geriatric_dp') {
          data[select_status.status + '_month'] = select_status.month
        } else {
          data[select_status.status + '_status_month'] = select_status.month
        }
      } else {
        if (select_status.status === 'geriatric_dp') {
          delete getProfile[select_status.status + '_month']
        } else {
          delete getProfile[select_status.status + '_status_month']
        }
      }
      console.log(data)
      this.setData({
        select_status: '',
        getProfile: Object.assign({}, getProfile, data)
      })
    }
      var params = new Object()
      params.business_param = {
          user_id: String(userLogin.user_id)
      }
      network.POST({
          params: params,
          url: "get_user_info",
          success: function (res) {
              var result = res.result[0] || {}
              var obj = {}
              obj.show_invest = result.show_invest
              that.setData({
                  getProfile: Object.assign({}, that.data.getProfile, obj)
              })
          },
          fail: function () {
              //失败后的逻辑

          },
      })
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  },
  upload_card: function () {
    const getProfile = JSON.stringify(this.data.getProfile || {})
    const userInfo = {
      real_name: getProfile.real_name,
      id_card: getProfile.id_card
    }
    wx.navigateTo({
      url: '../Information/Information?getProfile=' + JSON.stringify(userInfo)
    })
  },
  selectObjectDataKey: function (res) {
    this.data.ObjectData.forEach(v => {
      const findData = this.data[v + 'Array'].find(val => val.id === res[v])
      let data = {}
      data[v + 'Key'] = this.data[v + 'Array'].indexOf(findData)
      this.setData({
        selectKey: Object.assign({}, this.data.selectKey, data)
      })
    })
  },
  selectBindPickerChange: function (e) {
    const key = e.target.dataset.key
    const data = new Object()
    data[key] = e.detail.value
    this.setData({
      getProfile: Object.assign({}, this.data.getProfile, data)
    })
  },
  profileInput: function (e) {
    const key = e.target.dataset.key
    const data = new Object()
    data[key] = e.detail.value
    this.setData({
      getProfile: Object.assign({}, this.data.getProfile, data)
    })
  },
  selectObjectOrgBindPickerChange: function (e) {
    this.selectObjectBindPickerChange(e)
    if (!parseInt(e.detail.value)) {
      let getProfile = this.data.getProfile
      delete getProfile.org_lev
      this.setData({
        getProfile: getProfile
      })
      this.setData({
        selectKey: Object.assign({}, this.data.selectKey, {
          org_levKey: ''
        })
      })
    }
  },
  selectObjectBindPickerChange: function (e) {
    const key = e.target.dataset.key;
    const value = e.detail.value
    const data = new Object()
    const keyData = {}
    data[key] = this.data[key + 'Array'][value].id
    keyData[key + 'Key'] = parseInt(e.detail.value)
    this.setData({
      selectKey: Object.assign({}, this.data.selectKey, keyData)
    })
    this.setData({
      getProfile: Object.assign({}, this.data.getProfile, data)
    })
  },
  chooseImage: function (e) {
    var that = this
    app.globalData.leave = 1
    wx.chooseImage({
      count: 1,
      sizeType: ['compressed'], // 可以指定是原图还是压缩图，默认二者都有
      sourceType: ['album', 'camera'], // 可以指定来源是相册还是相机，默认二者都有
      success: function (res) {
        that.updateImg(res.tempFilePaths[0], '1')
        // wx.showLoading({
        //   title: '加载中',
        //   mask: true
        // })
        // util.canvasToBase.call(that, res.tempFilePaths[0], {
        //   width: 200,
        //   height: 200
        // }, function (base64) {
        //   wx.hideLoading()
        //   var userLogin = wx.getStorageSync('user_login') || {}
        //   var params = new Object()
        //   params.business_param = {}
        //   params.business_param.user_id = userLogin.user_id
        //   params.business_param.image_body = base64
        //   params.business_param.image_suffix = 'png'
        //   network.POST({
        //     params: params,
        //     url: "update_head_img",
        //     success: function (res) {
        //       that.setData({
        //         getProfile: Object.assign({}, that.data.getProfile, {
        //           head_pic: res.result[0].head_pic
        //         })
        //       })
        //       //拿到解密后的数据，进行代码逻辑
        //       app.globalData.leave = 0
        //     },
        //     fail: function () {
        //       //失败后的逻辑

        //     },
        //   })
        // })
      }
    })
  },
  updateImg: function (path, type) {
    wx.showToast({
      icon: "loading",
      title: "正在上传"
    })
    var userLogin = wx.getStorageSync('user_login') || {}
    var that = this;
    wx.uploadFile({
      url: network.UPLOAD_URL, //仅为示例，非真实的接口地址
      filePath: path,
      name: 'Key',
      header: {
        "Content-Type": "multipart/form-data"
      },
      formData: {
        "type": String(type) || '1',
        "user_id": String(userLogin.user_id)
      },
      success: function (res) {
        var data = res.data
        if (typeof data === 'string') {
          data = JSON.parse(data)
        }
        that.setData({
          getProfile: Object.assign({}, that.data.getProfile, {
            head_pic: data.result[0].head_pic
          })
        })
        wx.hideLoading()
      }
    })
  },
  saveUserInfo: function () {
    var that = this
    let show_invest1;
    try {
      //show_invest    1: 显示 0： 不显示
      show_invest1 = wx.getStorageSync('show_invest')
    } catch (e) {}
    if (this.data.getProfile.show_invest == 1) {
      wx.showToast({
        title: '请填写问卷调查',
        icon: 'none',
        duration: 2000
      })
      return
    }
    var userLogin = wx.getStorageSync('user_login') || {}
    var params = new Object()
    params.business_param = this.data.getProfile
    params.business_param.op_type = this.data.isPass ? 1 : 0
    // params.business_param.user_id = String(userLogin.user_id)
    network.POST({
      params: params,
      url: "update_info",
      success: function (res) {
        //拿到解密后的数据，进行代码逻辑
        if (!that.data.isPass) {
          wx.reLaunch({
            url: '../audit/audit'
          })
        } else {
          wx.navigateBack({
            delta: 1
          })
        }
      },
      fail: function () {
        //失败后的逻辑

      },
    })
  },
  goSelectDep: function (e) {
    console.log(e)
    const key = e.currentTarget.dataset.key
    const month_key = key === 'geriatric_dp' ? 'geriatric_dp_month' : 'psychiatry_status_month'
    const data = {}
    // data[key + '_status'] = this.data.getProfile[key + '_status'] || '';
    // data[month_key] = this.data.getProfile[month_key] || '';
    data['value'] = (this.data.getProfile[key + '_status'] === 1 || this.data.getProfile[key + '_status'] === 0) ? this.data.getProfile[key + '_status'] : '';
    data['month'] = this.data.getProfile[month_key] || '';
    data.status = key
    console.log(data)
    wx.navigateTo({
      url: '../department/department?data=' + JSON.stringify(data)
    })
  },
  goQuestionnaire: function () {
    wx.navigateTo({
      url: '../questionnaire/Questionnaire'
    })
  }
})